﻿using System;
using System.IO;
using System.Linq;

namespace CustomerContactSystem.WebForms.Enquiries.Documents {
    public partial class Delete : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id,documentid")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];

            CancelDeleteLink.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];
        }

        protected void SubmitDeletionClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id,documentid")) {
                return;
            }

            var documentId = int.Parse(Request.QueryString["documentid"]);
            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);
            var document = enquiry.Documents.SingleOrDefault(d => d.Id == documentId);

            if (document == null) {
                return;
            }

            var fileDeletePath = Server.MapPath("~/Docs" + document.SavePath() + document.FileName);
            
            enquiry.RemoveDocument(LoggedUser.DisplayName, documentId);

            EnquiryRepository.Update(enquiry);
            File.Delete(fileDeletePath);
            Response.Redirect("~/Enquiries/View.aspx?id=" + enquiry.Id);
        }
    }
}